<template>
  <div class="uploading">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
    >
      <img
        v-if="value"
        v-imgerror="imgerror"
        :src="value"
        class="avatar"
        @click.stop="preview"
      >
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <div v-if="value" class="del_img" @click="del">
      <i class="el-icon-delete" />
    </div>
    <!-- 图片预览弹窗 -->
    <el-dialog :visible.sync="isShow" title="图片预览" width="500px">
      <img v-imgerror="imgerror" style="width: 100%" :src="value" alt="">
    </el-dialog>
    <!-- 进度条 -->
    <transition name="fade">
      <el-progress v-if="isPercentage" :percentage="percentage" />
    </transition>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDqdFfuwjGZdRzIL8fy3tTothFbjbDaiaD',
  SecretKey: 'OXS8YjfLn0yhANL4Xkusc6KK4YmmX3JK'
})
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isShow: false,
      percentage: 0,
      isPercentage: false,
      imgerror: require('@/assets/common/bigUserHeader.png')
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === 'image/jpn' ||
        file.type === 'image/png' ||
        file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG、PNG、JPEG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    httpRequest(data) {
      this.percentage = 0
      this.isPercentage = true
      cos.putObject(
        {
          Bucket: 'hrm-1257315091' /* 存储桶 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: data.file.uid + '' /* 标识 */,
          StorageClass: 'STANDARD', // 固定值
          Body: data.file, // 上传文件对象  file文件对象
          onProgress: (progressData) => {
            // 上传进度，实时返回上传文件进度
            console.log(JSON.stringify(progressData))
            this.percentage = +(progressData.percent * 100).toFixed(2)
            if (progressData.percent === 1) {
              setTimeout(() => {
                this.isPercentage = false
              }, 800)
            }
          }
        },
        (err, data) => {
          // 上传成功或者失败处理
          // err为空就是成功，err有值就是失败了
          // data就是上传成功后腾讯云返回的数据（上传文件地址）
          if (!err) {
            this.$emit('input', 'http://' + data.Location)
          }
        }
      )
      // console.log('上传数据', data)
    },
    del() {
      this.$emit('input', '')
    },
    // 图片预览
    preview() {
      this.isShow = true
    }
  }
}
</script>

<style lang="scss" scoped>
.box {
  padding: 20px;
}
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #ccc;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.uploading {
  position: relative;
  width: 178px;
  height: 178px;
  &:hover {
    .del_img {
      display: block;
    }
  }
}
.del_img {
  position: absolute;
  display: none;
  top: 50%;
  right: 50%;
  margin-top: -15px;
  margin-right: -15px;
  i {
    font-size: 30px;
    color: #999;
  }
}
.el-progress {
  text-align: center;
}
.fade-enter-active,
.fade-leave-active {
  transition: all, 0.5;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
